<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="spu名称">
        <el-input v-model="spu.spuName" placeholder="请输入属性名" />
      </el-form-item>
      <el-form-item label="spu品牌">
        <el-select v-model="spu.tmId">
          <el-option
            v-for="(item, index) in allBrand"
            :key="index"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="spu描述">
        <el-input
          type="textarea"
          v-model="spu.description"
          placeholder="请输入描述"
        />
      </el-form-item>
      <el-form-item label="spu照片">
        <el-upload
          v-model:file-list="imgs"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeUpload"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            alt="图片"
            style="width: 500px; height: 500px"
          />
        </el-dialog>
      </el-form-item>

      <el-form-item label="spu销售属性">
        <!-- 展示销售属性的下拉菜单 -->
        <el-select
          v-model="saleAttrIdAndValueName"
          :placeholder="
            unSelectSaleAttr.length
              ? `还未选择${unSelectSaleAttr.length}个`
              : '无'
          "
        >
          <el-option
            :value="`${item.id}:${item.name}`"
            v-for="(item, index) in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-button
          @click="addSaleAttr"
          :disabled="saleAttrIdAndValueName ? false : true"
          style="margin-left: 10px"
          type="primary"
          size="default"
          icon="Plus"
        >
          添加属性
        </el-button>
        <el-table border style="margin: 20px 0px" :data="attrs">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名"
            width="100px"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="index"
                class="mx-1"
                closable
                style="margin-right: 5px"
                @close="tagColse($index, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-model="arrValue"
                @blur="handleBlur(row)"
                v-if="row.tag"
                placeholder="请输入属性值"
                size="small"
                style="width: 200px; margin-right: 5px"
              />
              <el-button
                @click="editAttValue(row)"
                v-else
                type="primary"
                size="small"
                icon="Plus"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100px">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrs.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpu">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/pro/spu.ts'
import { ElMessage } from 'element-plus'
// 声明自定义事件
let $emit = defineEmits(['changeScreen'])
// spu
let spu = reactive({
  category3Id: '',
  spuName: '',
  tmId: '',
  description: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
//属性值的增加标志
let addAttValueTag = ref(true)
//
let saleAttrIdAndValueName = ref('')
// 属性值input的值
let arrValue = ref('')
// 所有的品牌
let allBrand = ref([])
// 图片
let imgs = ref([])
// 属性
let attrs = ref([])
// 全部属性
let allAttrs = ref([])
//预览标志
let dialogVisible = ref(false)
//预览图片
let dialogImageUrl = ref('')
//暴露给父组件的方法
const getSpuInfo = async (spu1) => {
  const res = await reqAllTradeMark()
  const res1 = await reqSpuImageList(spu1.id)
  const res2 = await reqSpuHasSaleAttr(spu1.id)
  const res3 = await reqAllSaleAttr()
  allBrand.value = res.data
  if (res1.data && Array.isArray(res1.data)) {
    imgs.value = res1.data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  } else {
    imgs.value = []
  }
  attrs.value = res2.data
  allAttrs.value = res3.data
  Object.assign(spu, spu1)
}
//取消按钮的方法
const cancel = () => {
  $emit('changeScreen', { tag: 0, param: 'update' })
}
//编辑属性值的方法
const editAttValue = (row) => {
  //显示文本框
  row.tag = true
}
//失去焦点事件
const handleBlur = (row) => {
  if (arrValue.value.trim() == '') {
    ElMessage({
      message: '属性值不能为空',
      type: 'error',
    })
    return
  }
  if (
    row.spuSaleAttrValueList.filter(
      (item) => item.saleAttrValueName == arrValue.value,
    ).length > 0
  ) {
    ElMessage({
      message: '属性值重复',
      type: 'error',
    })
    return
  }
  let object = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: arrValue.value,
  }
  row.spuSaleAttrValueList.push(object)
  arrValue.value = ''
  row.tag = false
}
//添加属性
const addSaleAttr = () => {
  let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  attrs.value.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  })
  saleAttrIdAndValueName.value = ''
}
//计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  //全部销售属性:颜色、版本、尺码
  //已有的销售属性:颜色、版本
  let unSelectArr = allAttrs.value.filter((item) => {
    return attrs.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})
//图片预览的方法
const handlePictureCardPreview = (file) => {
  dialogVisible.value = true
  if (file.response.code == 200) {
    dialogImageUrl.value = file.response.data
  }
}
//上传图片之前的方法
const beforeUpload = (file) => {}
//关闭属性值的方法
const tagColse = (val1, val2) => {
  attrs.value[val1].spuSaleAttrValueList.splice(val2, 1)
}
//保存spu
const saveSpu = async () => {
  //图片
  spu.spuImageList = imgs.value.map((item) => {
    return {
      imgName: item.name,
      imgUrl: item.response != undefined ? item.response.data : item.url,
    }
  })
  //属性
  spu.spuSaleAttrList = attrs.value
  //调取保存方法
  let res = await reqAddOrUpdateSpu(spu)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: spu.id ? '更新成功' : '添加成功',
    })
    $emit('changeScreen', { tag: 0, param: spu.id ? 'update' : 'add' })
  } else {
    ElMessage({
      type: 'error',
      message: spu.id ? '更新失败' : '添加失败',
    })
  }
}
//新增初始化数据
const initSpuInfo = async (c3Id) => {
  //一进来清空数据
  delete spu.id
  ;(spu.category3Id = ''),
    (spu.spuName = ''),
    (spu.tmId = ''),
    (spu.description = ''),
    (spu.spuImageList = []),
    (spu.spuSaleAttrList = []),
    (imgs.value = [])
  attrs.value = []

  spu.category3Id = c3Id
  //发送两个请求
  const res = await reqAllTradeMark()
  const res1 = await reqAllSaleAttr()
  allBrand.value = res.data
  allAttrs.value = res1.data
}
//暴露出去
defineExpose({ getSpuInfo, initSpuInfo })
</script>
<style scoped lang="scss"></style>
